package com.crysta1.picviewer;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.viewpager2.widget.ViewPager2;

import com.bumptech.glide.Glide;

import java.io.IOException;
import java.io.OutputStream;

public class DetailActivity extends AppCompatActivity {
    private ViewPager2 viewPager;
    private LinearLayout bottomToolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);

        viewPager = findViewById(R.id.view_pager);
        bottomToolbar = findViewById(R.id.bottom_toolbar);

        // 获取传递的数据
        int position = getIntent().getIntExtra("position", 0);
        viewPager.setAdapter(new ImagePagerAdapter(this,MainActivity.imageList));
        viewPager.setCurrentItem(position);

        // 点击图片切换工具条可见性
        viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                setupToolbarActions(position);
            }
        });

        setupToolbarActions(position);
    }

    private void setupToolbarActions(int position) {
        findViewById(R.id.btn_back).setOnClickListener(v -> finish());

        findViewById(R.id.btn_delete).setOnClickListener(v -> {
            MainActivity.imageList.remove(position);
            finish();
        });

        findViewById(R.id.btn_save).setOnLongClickListener(v -> {
            ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("URL", MainActivity.imageList.get(position).url);
            clipboard.setPrimaryClip(clip);
            Toast.makeText(this, "URL已复制", Toast.LENGTH_SHORT).show();
            saveImageToGallery();
            return true;
        });

        // 处理保存按钮点击
//        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
//                != PackageManager.PERMISSION_GRANTED) {
//            ActivityCompat.requestPermissions(this, newManifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_CODE_STORAGE_PERMISSION);
//    } else {
//        saveImageToGallery();
//    }
    }



// 处理权限请求结果
//@Override
//public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//    if (requestCode == REQUEST_CODE_STORAGE_PERMISSION) {
//        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//            saveImageToGallery();
//        } else {
//            Toast.makeText(this, "需要存储权限才能保存图片", Toast.LENGTH_SHORT).show();
//        }
//    }
//}

private void saveImageToGallery() {
    int currentPosition = viewPager.getCurrentItem();
    String imageUrl = MainActivity.imageList.get(currentPosition).url;

    new Thread(() -> {
        try {
            Bitmap bitmap = Glide.with(this)
                    .asBitmap()
                    .load(imageUrl)
                    .submit()
                    .get();

            saveBitmapToGallery(bitmap);
        } catch (Exception e) {
            runOnUiThread(() ->
                    Toast.makeText(this, "保存失败: " + e.getMessage(), Toast.LENGTH_SHORT).show());
        }
    }).start();
}

private void saveBitmapToGallery(Bitmap bitmap) {
    String displayName = "IMG_" + System.currentTimeMillis() + ".jpg";

    ContentValues values = new ContentValues();
    values.put(MediaStore.Images.Media.DISPLAY_NAME, displayName);
    values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        values.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);
    }

    ContentResolver resolver = getContentResolver();
    Uri uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

    try (OutputStream out = resolver.openOutputStream(uri)) {
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
        runOnUiThread(() ->
                Toast.makeText(this, "图片已保存到相册", Toast.LENGTH_SHORT).show());
    } catch (IOException e) {
        runOnUiThread(() ->
                Toast.makeText(this, "保存失败: " + e.getMessage(), Toast.LENGTH_SHORT).show());
    }
}

    

}